package com.zzedu.manager.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20210111.models.SendStatus;
import com.zzedu.common.enums.CommonEnums;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.domain.ZzSendMsg;
import com.zzedu.domain.ZzStudent;
import com.zzedu.enmuns.VerificationCodeEnums;
import com.zzedu.integration.sms.ISmsClientService;
import com.zzedu.manager.IZzSendMsgManager;
import com.zzedu.result.Result;
import com.zzedu.result.ResultEnum;
import com.zzedu.service.IZzSendMsgService;
import com.zzedu.service.IZzStudentService;
import com.zzedu.system.service.ISysConfigService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;

/**
 * 短信发送服务
 */
@Service
public class ZzSendMsgManagerImpl implements IZzSendMsgManager {

    private Logger logger = LoggerFactory.getLogger(IZzSendMsgManager.class);
    @Autowired
    IZzSendMsgService zzSendMsgService;

    @Autowired
    ISmsClientService smsClientService;

    @Autowired
    IZzStudentService zzStudentService;

    @Autowired
    ISysConfigService sysConfigService;

    @Override
    public Result sendVerificationCode(String tel, VerificationCodeEnums verificationCodeEnums) {
        Result result = new Result<>();
        result.setResultCode(ResultEnum.SUCCESS.getCode());
        result.setResultMessage(ResultEnum.SUCCESS.getDesc());
        Assert.isTrue(StringUtils.isNotBlank(tel), "手机号不能为空");
        Assert.notNull(verificationCodeEnums, "验证码类型");
        ZzStudent zzStudent = zzStudentService.getOne(Wrappers.lambdaQuery(ZzStudent.class).eq(ZzStudent::getTel, tel).last("limit 1 "));
        Assert.notNull(zzStudent, "未找到该手机号对应学生信息");
        Long sendCount = zzSendMsgService.getCountByPhone(tel, LocalDateTime.now().plusHours(-1), LocalDateTime.now());
        String limitCountStr = sysConfigService.selectConfigByKeyCache(verificationCodeEnums.getCode());
        Long limitCount = 5L;
        if (StringUtils.isNotBlank(limitCountStr)) {
            limitCount = Long.valueOf(limitCountStr);
        }
        Assert.isTrue(sendCount < limitCount, "该手机号获取验证码次数超限,请过会儿在来");
        String code = RandomStringUtils.secure().nextNumeric(6);
        ZzSendMsg zzSendMsg = new ZzSendMsg();
        zzSendMsg.setContent(code);
        zzSendMsg.setPhone(tel);
        zzSendMsg.setSmsType(verificationCodeEnums.getCode());
        zzSendMsg.setIsUsed(CommonEnums.NO.getCode());
        zzSendMsg.setResult(1);
        zzSendMsg.setSourceIp(SecurityUtils.getIp());
        zzSendMsg.setExpireAt(LocalDateTime.now().plusMonths(5L));
        zzSendMsgService.save(zzSendMsg);
        SendSmsResponse sendSmsResponse = smsClientService.sendMsg(new String[]{tel}, new String[]{code}, verificationCodeEnums.getTemplateId());
        if (sendSmsResponse == null) {
            zzSendMsg.setResult(4);
            zzSendMsgService.updateById(zzSendMsg);
            result.setResultCode(ResultEnum.FAIL.getCode());
            result.setResultMessage(ResultEnum.FAIL.getDesc());
            result.setData("未收到短信服务商回执");
            return result;
        }
        SendStatus[] sendStatusSet = sendSmsResponse.getSendStatusSet();
        SendStatus sendStatus = sendStatusSet[0];
        if ("Ok".equalsIgnoreCase(sendStatus.getCode())) {
            zzSendMsg.setResult(3);
            zzSendMsgService.updateById(zzSendMsg);
        } else {
            zzSendMsg.setResult(2);
            zzSendMsgService.updateById(zzSendMsg);
            result.setResultCode(ResultEnum.FAIL.getCode());
            result.setResultMessage(ResultEnum.FAIL.getDesc());
            result.setData("发送短信失败,请联系平台管理员");
            return result;
        }
        return result;
    }
}
